package org.example.service.impl;
import org.example.entity.CourseCollect;
import org.example.entity.Result;
import org.example.entity.User;
import org.example.mapper.CourseCollectMapper;
import org.example.mapper.UserMapper;
import org.example.service.CourseCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ClassName CourseCollectServiceImpl
 * @Description TODO
 * @Author qiuye
 * @Date 2025年08月15日 17:17
 * @Version 1.0
 */
@Service
public class CourseCollectServiceImpl implements CourseCollectService {
    @Autowired
    private CourseCollectMapper courseCollectMapper;


    @Override
    public List<CourseCollect> getByCourse(int id) {
        List<CourseCollect> Courses = courseCollectMapper.getByCourse(id);
        return Courses;
    }
    @Autowired
    private UserMapper userMapper;
    @Override
    public Result sc(int userId, int courseId) {
        // 1. 检查是否已收藏
        Integer count = courseCollectMapper.countByUserAndCourse(userId, courseId);
        if (count != null && count > 0) {
            return Result.error("重复收藏"); // code=500，msg=重复收藏
        }

        // 2. 执行收藏
        int i = courseCollectMapper.add(userId, courseId);
        if (i <= 0) {
            return Result.error("收藏失败");
        }

        // 3. 增加积分
        User user = userMapper.findUserById(userId);
        if (user == null) {
            return Result.error("用户不存在");
        }
        int newPoints = user.getPoints() + 10;
        userMapper.updatePoints(userId, newPoints);

        // 4. 返回新积分
        return Result.success("收藏成功", newPoints);
    }

    @Override
    public Result deleteByUserAndCourse(int userId, int courseId) {
        // 1. 检查是否已收藏（可选，避免重复删除）
        Integer count = courseCollectMapper.countByUserAndCourse(userId, courseId);
        if (count == null || count == 0) {
            return Result.error("未收藏，无法取消");
        }

        // 2. 执行取消收藏（删除记录）
        int i = courseCollectMapper.deleteByUserAndCourse(userId, courseId);
        if (i <= 0) {
            return Result.error("取消收藏失败");
        }

        return Result.success("取消收藏成功");

    }

    @Override
    public boolean isCollected(int userId, int courseId) {
        Integer count = courseCollectMapper.countByUserAndCourse(userId, courseId);
        return count != null && count > 0;
    }
}
